<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;

class UserViewLog extends Model
{
    protected function getOptions(): array
    {
        return [
            'autoWriteTimestamp' => true,
            'createTime'         => 'create_time',
            'updateTime'         => false,
            'jsonAssoc'          => true,
        ];
    }

    /**
     * 关联用户
     */
    public function user()
    {
        return $this->belongsTo('User', 'user_id');
    }

    /**
     * 获取用户浏览记录
     * @param int $userId 用户ID
     * @param string $contentType 内容类型，为空则获取所有类型
     * @param string $date 日期，格式：Y-m-d，为空则获取所有日期
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array
     */
    public static function getUserViewLogs($userId, $contentType = '', $date = '', $page = 1, $limit = 10)
    {
        $query = self::where('user_id', $userId);

        if (!empty($contentType)) {
            $query->where('content_type', $contentType);
        }

        if (!empty($date)) {
            $query->where('view_date', $date);
        }

        $total = $query->count();

        $logs = $query->order('create_time', 'desc')
            ->page($page, $limit)
            ->select()
            ->toArray();

        return [
            'total' => $total,
            'data'  => $logs,
        ];
    }

    /**
     * 获取用户今日浏览次数
     * @param int $userId 用户ID
     * @param string $contentType 内容类型，为空则获取所有类型
     * @return int
     */
    public static function getUserTodayViewCount($userId, $contentType = '')
    {
        $query = self::where('user_id', $userId)
            ->where('view_date', date('Y-m-d'));

        if (!empty($contentType)) {
            $query->where('content_type', $contentType);
        }

        return $query->count();
    }

    /**
     * 获取用户浏览统计
     * @param int $userId 用户ID
     * @return array
     */
    public static function getUserViewStats($userId)
    {
        // 总浏览次数
        $totalCount = self::where('user_id', $userId)->count();

        // 今日浏览次数
        $todayCount = self::getUserTodayViewCount($userId);

        // 按类型统计
        $typeStats = [];
        $types     = ['chapter', 'file', 'group'];

        foreach ($types as $type) {
            $typeStats[$type] = [
                'total' => self::where('user_id', $userId)
                    ->where('content_type', $type)
                    ->count(),
                'today' => self::getUserTodayViewCount($userId, $type),
            ];
        }

        // 最近7天浏览统计
        $dayStats = [];
        for ($i = 6; $i >= 0; $i--) {
            $date            = date('Y-m-d', strtotime("-$i days"));
            $dayStats[$date] = self::where('user_id', $userId)
                ->where('view_date', $date)
                ->count();
        }

        return [
            'total_count' => $totalCount,
            'today_count' => $todayCount,
            'type_stats'  => $typeStats,
            'day_stats'   => $dayStats,
        ];
    }

    /**
     * 记录用户浏览
     * @param int $userId 用户ID
     * @param string $contentType 内容类型
     * @param int $contentId 内容ID
     * @return bool
     */
    public static function recordView($userId, $contentType, $contentId)
    {
        $today = date('Y-m-d');

        // 检查今天是否已记录
        $exist = self::where('user_id', $userId)
            ->where('content_type', $contentType)
            ->where('content_id', $contentId)
            ->where('view_date', $today)
            ->find();

        if ($exist) {
            return true;
        }

        // 创建记录
        return self::create([
            'user_id'      => $userId,
            'content_type' => $contentType,
            'content_id'   => $contentId,
            'view_date'    => $today,
            'create_time'  => date('Y-m-d H:i:s')
        ]) ? true : false;
    }
}